package com.gandong8.trace.tool.core;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class TraceAware implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        TraceAware.applicationContext = applicationContext;
    }


    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> clazz) {
        return applicationContext.getBeansWithAnnotation(clazz);
    }

    @SuppressWarnings({ "unchecked"})
    public static List<Method> getClassMethodByAnnotation(Class clazz, Class annotationClazz) throws Exception {
        clazz = Class.forName(clazz.getName(), true, clazz.getClassLoader());
        List<Method> result = new ArrayList<>();
        for (Method method : clazz.getMethods()) {
            if (method.getAnnotation(annotationClazz) != null) {
                result.add(clazz.getMethod(method.getName(), method.getParameterTypes()));
            }
        }
        return result;
    }
}
